<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="药品名称" prop="drugsName">
        <el-input
          v-model="queryParams.drugsName"
          placeholder="请输入药品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="药品种类" prop="drugsKind">
        <el-select
          v-model="queryParams.categoryId"
          placeholder="药品类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.categoryId"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['drugs:drugs:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['drugs:drugs:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['drugs:drugs:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['drugs:drugs:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="drugsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="药品编号" align="center" prop="drugsId" />
      <el-table-column label="药品名称" align="center" prop="drugsName" />
      <el-table-column label="药品图片" align="center" prop="drugsImg">
        <template slot-scope="scope">
          <img :src="scope.row.drugsImg" width="70" height="70" />
        </template>
      </el-table-column>
      <el-table-column label="药品类型" align="center" prop="categoryName" v-if="false"/>
      <el-table-column label="药品价格" align="center" prop="drugsPrice" />
      <el-table-column label="药品数量" align="center" prop="drugsCount" />
      <el-table-column label="进货人" align="center" prop="purchaserName" />
      <el-table-column label="进货人手机号" align="center" prop="purchaserPhone" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['drugs:drugs:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['drugs:drugs:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改药品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="药品名称" prop="drugsName">
          <el-input v-model="form.drugsName" placeholder="请输入药品名称" />
        </el-form-item>
        <el-form-item label="药品价格" prop="drugsPrice">
          <el-input v-model="form.drugsPrice" placeholder="请输入药品价格" />
        </el-form-item>
        <el-form-item label="药品种类" prop="categoryIds">
          <el-select v-model="form.categoryIds" multiple placeholder="请选择药品种类">
            <el-option
                v-for="item in categoryOptions"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药品数量" prop="drugsCount">
          <el-input v-model="form.drugsCount" placeholder="请输入药品数量" />
        </el-form-item>
        <el-form-item label="药品图片" prop="drugsImg">
          <el-upload
            class="avatar-uploader"
            ref="uploadfile"
            :headers="headers"
            action="http://localhost:8080/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="进货人" prop="purchaserName">
          <el-input v-model="form.purchaserName" placeholder="请输入进货人" />
        </el-form-item>
        <el-form-item label="进货人手机号" prop="purchaserPhone">
          <el-input v-model="form.purchaserPhone" placeholder="请输入进货人手机号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDrugs, getDrugs, delDrugs, addDrugs, updateDrugs } from "@/api/drugs/drugs";
import {getToken} from "@/utils/auth"

export default {
  name: "Drugs",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 药品表格数据
      drugsList: [],
      //种类选项
      categoryOptions:[],
      imageUrl: "",
      // // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        drugsName: null,
        drugsPrice: null,
        categoryId: null,
        categoryName: null,
        drugsCount: null,
        imageUrl: null,
        purchaserName: null,
        purchaserPhone: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        drugsName: [
          { required: true,pattern: /^.{1,20}$/, message: "药品名称在1-20字符之间", trigger: "blur" }
        ],
        drugsPrice: [
          { required: true, pattern: /^\d+(\.\d{1,2})?$/,message: "药品价格是正数且最多包含两位小数", trigger: "blur" }
        ],
        drugsCount: [
          { required: true,pattern: /^\d{1,5}$/, message: "药品数量在0-99999之间", trigger: "blur" }
        ],
        purchaserName: [
          { required: true,pattern: /^.{1,20}$/, message: "进货人在1-20字符之间", trigger: "blur" }
        ],
        categoryIds: [
          { required: true, message: "药品类型不能为空", trigger: "blur" }
        ],
        purchaserPhone: [
          { required: true,pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "手机号格式错误", trigger: "blur" }
        ],
        drugsImg: [
          { required: true, message: "药品图片不能为空", trigger: "blur" }
        ],
      },
      headers: {Authorization: getToken()},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询药品列表 */
    getList() {
      this.loading = true;
      getDrugs().then(response => {
        this.categoryOptions = response.drugcategories;
      });
      listDrugs(this.queryParams).then(response => {
        this.drugsList = response.rows;
        // console.log(this.drugsList);
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        drugsId: null,
        drugsName: null,
        drugsPrice: null,
        categoryId: null,
        categoryIds:[],
        drugsCount: null,
        drugsImg: null,
        purchaserName: null,
        purchaserPhone: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.drugsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.imageUrl = ''
      getDrugs().then(response => {
        this.categoryOptions = response.drugcategories;
        this.open = true;
        this.title = "添加药品";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const drugsId = row.drugsId || this.ids
      getDrugs(drugsId).then(response => {
        this.form = response.data;
        this.imageUrl = response.data.drugsImg
        this.categoryOptions = response.drugcategories;
        this.$set(this.form, "categoryIds", response.categoryIds);
        this.open = true;
        this.title = "修改药品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.drugsImg = this.imageUrl
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.drugsId != null) {
            updateDrugs(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDrugs(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const drugsIds = row.drugsId || this.ids;
      this.$modal.confirm('是否确认删除药品编号为"' + drugsIds + '"的数据项？').then(function() {
        return delDrugs(drugsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('drugs/drugs/export', {
        ...this.queryParams
      }, `drugs_${new Date().getTime()}.xlsx`)
    },
    /**上传图片 */
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.data
    },
    beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
  }
};
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
</style>
